package core

import (
	"gitee.com/lvshicong/blog/global"
	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/plugin/dbresolver"
	"time"
)

func InitDB() *gorm.DB {
	g1 := global.Config.Db1 //写库
	g2 := global.Config.Db2 //读库

	db, err := gorm.Open(mysql.Open(g1.GetDSN()), &gorm.Config{})
	if err != nil {
		logrus.Panicln("数据库连接失败", err)
	}
	logrus.Println("数据库连接成功")
	//配置数据库连接池
	sqlDB, err := db.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)
	//如果g2为空，则不配置读写分离
	if !g2.Empty() {
		//配置读写分离
		err := db.Use(dbresolver.Register(dbresolver.Config{
			// use `db2` as sources, `db3`, `db4` as replicas
			Sources:           []gorm.Dialector{mysql.Open(g1.GetDSN())},
			Replicas:          []gorm.Dialector{mysql.Open(g2.GetDSN())},
			Policy:            dbresolver.RandomPolicy{},
			TraceResolverMode: true,
		}))
		if err != nil {
			logrus.Panicln("数据库读写分离配置失败", err)
		}
		logrus.Println("数据库读写分离配置成功")
	}
	return db
}
